package com.example.lt.util;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.ExecutorService;

/**
 * @Author 小涛Tao
 * @Date: 2024/07/28/9:44
 * version 1.0 注释：邮箱工具类，提供发送邮箱方法
 **/
@Service(value = "emailUtil")
public class EmailUtil {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private ExecutorService executorService;

    @Setter
    @Getter
    @Value("${spring.mail.properties.mail.from}")
    private String from;

    /*账号注册验证码发送*/
    public void sendRegisterCode(String to, String code) {
        // 把发送邮件交给线程池去执行
        executorService.submit(() -> {
            try {
                // 创建一个 MimeMessage 对象
                MimeMessage mimeMessage = mailSender.createMimeMessage();
                // 使用 MimeMessageHelper 来设置邮件内容
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");

                // 设置发送方
                helper.setFrom(from);
                // 设置接收方
                helper.setTo(to);
                // 设置邮件主题
                helper.setSubject("\"悦动瞬间\"账号注册验证码");

                // 构建 HTML 格式的邮件内容
                String htmlContent = "<html><body>";
                htmlContent += "<h1 style=\"color: #0099ff;\">欢迎注册\"JoyfulMoments\"平台</h1>";
                htmlContent += "<p>您的注册验证码是：<span style=\"font-size: 20px; font-weight: bold;\">" + code + "</span></p>";
                htmlContent += "<p>验证码时效为5分钟，请在注册页面输入该验证码完成注册。</p>";
                htmlContent += "</body></html>";

                // 设置邮件内容为 HTML 格式
                helper.setText(htmlContent, true);

                // 发送邮件
                mailSender.send(mimeMessage);
            } catch (MessagingException e) {
                // 处理邮件发送异常
                e.printStackTrace();
                // 或者记录日志等其他操作
            }
        });
    }

}
